package com.kehutong.payment.vo;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.coraframework.json.annotation.JSONField;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;

/**
 * @author liuzhen (liuxing521a@163.com)
 * @createTime 2020年7月9日下午7:26:51
 */
public class Merchant {
	
	private static final Logger logger = LoggerFactory.getLogger(Merchant.class);
	
	public Merchant(String appId,
			String mchId,
			String mchName,
			String mchSecret,
			String subAppid,
			String subMchId,
			String subMchName, 
			InputStream certInput) {
		try {
			this.appId = appId;
			this.subAppid = subAppid;
			this.mchId = mchId;
			this.mchName = mchName;
			this.mchSecret = mchSecret;
			if (!mchId.equals(subMchId)) {
				this.subMchId = subMchId;
				this.subMchName = subMchName;
			} else {
				this.subMchId = "";
				this.subMchName = "";
			}
			this.certInput = certInput;
			this.sslContext = getKmsFactory();
		} catch (Exception e) {
			logger.error("", e);
			throw new RuntimeException(String.format("get pay cert file err, mchid:%s, appId:%s", mchId, appId));
		}
	}
	
	//公众号id
	private final String appId;

	//子商户号公众号id
	private String subAppid;

	//子商户id
	private final String subMchId;
	
	//子商户名称
	private final String subMchName;
	
	// 商户id
	private final String mchId;

	// 商户名称 小区名或物业公司名
	private final String mchName;

	// 商户密约
	@JSONField(serialize=false)
	private final String mchSecret;
	
	// 支付文件
	@JSONField(serialize=false)
	private final InputStream certInput;

	@JSONField(serialize=false)
	private final SSLContext sslContext;
	
	public String getAppId() {
		return appId;
	}

	public String getSubAppid() {
		return subAppid;
	}

	public String getSubMchName() {
		return subMchName;
	}

	public String getMchId() {
		return mchId;
	}

	public String getMchName() {
		return mchName;
	}

	public String getMchSecret() {
		return mchSecret;
	}
	
	public String getSubMchId() {
		return subMchId;
	}


	public InputStream getCertInput() {
		return certInput;
	}
	
	public SSLContext getSslContext() {
		return sslContext;
	}

	private SSLContext getKmsFactory() throws Exception {
		//证书，密码是商户id
		char[] password = mchId.toCharArray();
        InputStream certStream = certInput;
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(certStream, password);
//        certStream.close();//关流
        // 实例化密钥库 & 初始化密钥工厂
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, password);
        
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
        
        return sslContext;
	}

}
